<template>
    <div :data-upload-id="uploaderId" style="display:inline">
        <input ref="uploader" @change="onFileChange" style="opacity:0;position:fixed;left:100%;" type="file" :accept="accept" :id="uploaderId" :multiple="multiple">
        <slot name="list"></slot>
        <label ref="uploaderlabel" :for="uploaderId" style="cursor: pointer;display:block;width:0">
            <slot></slot>
        </label>
    </div>
</template>

<script>
import { randomString } from '@/utils'
export default {
    props: {
        accept: {
            type: String,
            default: 'image/*'
        },
        multiple: {
            type: Boolean,
            default: false
        }
    },
    computed: {
        uploaderId() {
            return randomString(10)
        }
    },
    data() {
        return {
            file: null
        }
    },
    methods: {
        onFileChange(e) {
            console.log('onFileChange', e.target.files)

            var files = e.target.files
            var urls = []
            for (let i = 0; i < files.length; i++) {
                urls.push(URL.createObjectURL(files[i]))
            }
            this.$emit('on-select', {
                files: e.target.files,
                localUrls: urls
            })
            setTimeout(() => {
                this.$refs.uploader.value = ''
            }, 10)
        },
        reSelect() {
            this.$refs.uploaderlabel.click()
        }
    }
}
</script>

<style>
</style>
